package com.loong.musicdemo.ui.find.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.loong.musicdemo.R;
import com.loong.musicdemo.model.SearchInfo;
import com.loong.musicdemo.util.dataDeal.SearchDeal;
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private MaterialSearchView searchView;
    private List<String> historyRecord= new ArrayList<>();
    private SharedPreferences historyPreference;
    private RecyclerView record_view,hot_search_view,search_suggest_list;
    private HistoryAdapter historyAdapter;
    private SuggestionAdapter  suggestionAdapter;
    private RelativeLayout history_content;
    private ImageView clear_history;
    private List<String> searchSuggestions= new ArrayList<>();
    private List<SearchInfo> searchInfoList= new ArrayList<>();
    private HotSearchAdapter hotAdapter;
    private LinearLayout search_main_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        setContentView(R.layout.activity_search);
        initView();
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("搜索");
            actionBar.setDisplayHomeAsUpEnabled(true);//若工具栏可用,则显示Home菜单
        }
        initHistoryRecord();
        initRecordView();
        initHotSearchView();
        initSearchSuggestionView();
        new SearchTask().execute();
    }

    /*
        初始化所有的控件
     */
    private void initView(){
        searchView = findViewById(R.id.search_view);
        toolbar = findViewById(R.id.toolbar);
        historyPreference = getSharedPreferences("history",MODE_PRIVATE);
        record_view = findViewById(R.id.record_view);
        historyAdapter = new HistoryAdapter(historyRecord);
        suggestionAdapter = new SuggestionAdapter(searchSuggestions);
        hotAdapter = new HotSearchAdapter(searchInfoList);
        history_content = findViewById(R.id.history_content);
        hot_search_view = findViewById(R.id.hot_search_view);
        clear_history = findViewById(R.id.clear_history);
        search_suggest_list = findViewById(R.id.search_suggest_list);
        search_main_content = findViewById(R.id.search_main_content);
    }
    //初始化历史记录
    private void initHistoryRecord(){
        int historySize = historyPreference.getInt("historySize",0);
        if(historySize != 0){
            for(int i = 0;i<historySize;i++){
                String item = historyPreference.getString("history_"+i, null);
                historyRecord.add(item);
            }
        }
    }
    //初始化历史记录RecyclerView
    private void initRecordView(){
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        record_view.setLayoutManager(layoutManager);
        record_view.setAdapter(historyAdapter);
        if(historyRecord.size()!=0){
            history_content.setVisibility(View.VISIBLE);
        }else {
            history_content.setVisibility(View.GONE);
        }
        initClearHistoryHandler();
    }

    private void initHotSearchView(){
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        hot_search_view.setLayoutManager(layoutManager);
        hot_search_view.setAdapter(hotAdapter);
    }

    //初始化搜索建议recyclerview
    private void initSearchSuggestionView(){
        LinearLayoutManager manager = new LinearLayoutManager(getApplicationContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        search_suggest_list.setLayoutManager(manager);
        search_suggest_list.setAdapter(suggestionAdapter);
        if(searchSuggestions.size() == 0){
            search_suggest_list.setVisibility(View.GONE);
            search_main_content.setVisibility(View.VISIBLE);
        }else {
            search_suggest_list.setVisibility(View.VISIBLE);
            search_main_content.setVisibility(View.GONE);
        }
    }
    class SuggestionAdapter extends RecyclerView.Adapter<SuggestionAdapter.ViewHodler>{
        private List<String> suggestions;

        public SuggestionAdapter(List<String> suggestions) {
            this.suggestions = suggestions;
        }

        @NonNull
        @Override
        public SuggestionAdapter.ViewHodler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.search_suggestion_item,parent,false);
            ViewHodler hodler = new ViewHodler(view);
            return hodler;
        }

        @Override
        public void onBindViewHolder(@NonNull SuggestionAdapter.ViewHodler holder, int position) {
            holder.search_keyword.setText(suggestions.get(position));

                holder.view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getAdapterPosition();
                        String keywords = suggestions.get(pos);
                        if(!keywords.equals("暂无数据")){
                            Intent intent = new Intent(getApplicationContext(), SearchResultActivity.class);
                            intent.putExtra("resultName",suggestions.get(pos));
                            startActivity(intent);
                        }else {
                            Toast.makeText(getApplicationContext(),"无结果",Toast.LENGTH_LONG).show();
                        }

                    }
                });

        }

        @Override
        public int getItemCount() {
            return suggestions.size();
        }

        public class ViewHodler extends RecyclerView.ViewHolder {
            TextView search_keyword;
            View view;
            public ViewHodler(@NonNull View itemView) {
                super(itemView);
                view = itemView;
                search_keyword = itemView.findViewById(R.id.search_keyword);
            }
        }
    }
    //清空历史的点击事件
    private void initClearHistoryHandler(){
        clear_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new QMUIDialog.MessageDialogBuilder(SearchActivity.this)
                        .setTitle("标题")
                        .setMessage("确定要删除吗？")
                        .addAction("取消", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                            }
                        })
                        .addAction(0, "删除", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                SharedPreferences.Editor editor = historyPreference.edit();
                                editor.clear();
                                editor.apply();
                                historyRecord.clear();
                                historyAdapter.notifyDataSetChanged();
                                history_content.setVisibility(View.GONE);
                                dialog.dismiss();
                            }
                        }).show();
            }
        });
    }
    class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.ViewHolder>{
        List<String> historyList ;

        public HistoryAdapter(List<String> historyList) {
            this.historyList = historyList;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.search_history_item,parent,false);
            ViewHolder hodler = new ViewHolder(view);
            return hodler;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            String content = historyList.get(position);
            holder.history.setText(content);
            holder.root.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getApplicationContext(), SearchResultActivity.class);
                    intent.putExtra("resultName",content);
                    startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return historyList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView history;
            View root;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                root = itemView;
                history = itemView.findViewById(R.id.history);
            }
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search_view,menu);
        MenuItem item = menu.findItem(R.id.action_search);
        searchView.setMenuItem(item);
        initSearchViewHandler();
        return super.onCreateOptionsMenu(menu);
    }

    //将搜索记录加入到历史记录
    private void addToHistoryRecord(String query){
        historyRecord.add(query);
        SharedPreferences.Editor editor = historyPreference.edit();
        //存取长度
        editor.putInt("historySize",historyRecord.size());
        //每次只存取最后一个
        editor.putString("history_"+(historyRecord.size()-1),query);
        editor.apply();
        historyAdapter.notifyDataSetChanged();
    }
    //添加searchView的事件监听器
    private void initSearchViewHandler(){
        searchView.setVoiceSearch(true);
        searchView.showSearch();
        searchView.setCursorDrawable(R.drawable.color_cursor_white);
        searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if(!historyRecord.contains(query)){
                    addToHistoryRecord(query);
                }
                history_content.setVisibility(View.VISIBLE);
                Intent intent = new Intent(getApplicationContext(),SearchResultActivity.class);
                intent.putExtra("resultName",query);
                startActivity(intent);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (!TextUtils.isEmpty(newText)) {
                    search_suggest_list.setVisibility(View.VISIBLE);
                    search_main_content.setVisibility(View.GONE);
                    new SuggestionTask(newText).execute();
                } else {
                    search_suggest_list.setVisibility(View.GONE);
                    search_main_content.setVisibility(View.VISIBLE);
                }
                return false;
            }
        });

        searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
            @Override
            public void onSearchViewShown() {
            }

            @Override
            public void onSearchViewClosed() {
            }
        });
    }

    class SuggestionTask extends AsyncTask<String,Void,List<String>>{
        private String keyword;

        public SuggestionTask(String keyword) {
            this.keyword = keyword;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(List<String> strings) {
            super.onPostExecute(strings);
            searchSuggestions.clear();
            searchSuggestions.addAll(strings);
            suggestionAdapter.notifyDataSetChanged();
        }

        @Override
        protected List<String> doInBackground(String... strings) {
            return SearchDeal.getSearchSuggestions(keyword);
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;//返回前一个活动
        }
        return super.onOptionsItemSelected(item);
    }

    class SearchTask extends AsyncTask<SearchInfo,Void,List<SearchInfo>>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(List<SearchInfo> searchInfos) {
            super.onPostExecute(searchInfos);
            searchInfoList.addAll(searchInfos);
            hotAdapter.notifyDataSetChanged();
        }

        @Override
        protected List<SearchInfo> doInBackground(SearchInfo... searchInfos) {
            return SearchDeal.getSearchHotDetail();
        }
    }
    @Override
    public void onBackPressed() {
        if (searchView.isSearchOpen()) {
            searchView.closeSearch();
        } else {
            super.onBackPressed();
        }
    }
    class HotSearchAdapter extends RecyclerView.Adapter<HotSearchAdapter.ViewHolder> {
        private List<SearchInfo> searchInfoList;

        public HotSearchAdapter(List<SearchInfo> searchInfoList) {
            this.searchInfoList = searchInfoList;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hot_search_info_item,parent,false);
            ViewHolder holder = new ViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            SearchInfo searchInfo = searchInfoList.get(position);
            holder.search_content.setText(searchInfo.getContent());
            if(position == 0 || position == 1||position==2){
                holder.search_order.setTextColor(Color.RED);
            }
            holder.search_order.setText(position+1+"");
            holder.search_score.setText(searchInfo.getScore());
            holder.search_word.setText(searchInfo.getSearchWord());
            if(searchInfo.getIconUrl()!=null){
                Glide.with(getApplicationContext()).load(searchInfo.getIconUrl()).diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true).into(holder.search_icon);
            }
            holder.root.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = holder.getAdapterPosition();
                    SearchInfo si = searchInfoList.get(pos);
                    if(!historyRecord.contains(si.getSearchWord())){
                        addToHistoryRecord(si.getSearchWord());
                    }
                    Intent intent = new Intent(getApplicationContext(), SearchResultActivity.class);
                    intent.putExtra("resultName",si.getSearchWord());
                    startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return searchInfoList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            View root;
            TextView search_order,search_word,search_content,search_score;
            ImageView search_icon;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                root = itemView;
                search_content = itemView.findViewById(R.id.search_content);
                search_order = itemView.findViewById(R.id.search_order);
                search_word = itemView.findViewById(R.id.search_word);
                search_score = itemView.findViewById(R.id.search_score);
                search_icon = itemView.findViewById(R.id.search_icon);
            }
        }
    }


}
